package org.example.lanchain.config;

import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import dev.langchain4j.store.embedding.pinecone.PineconeEmbeddingStore;
import dev.langchain4j.store.embedding.pinecone.PineconeServerlessIndexConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EmbeddingStoreConfig {

    private static final Logger logger = LoggerFactory.getLogger(EmbeddingStoreConfig.class);

    @Autowired
    private EmbeddingModel embeddingModel;

    @Bean
    public EmbeddingStore<TextSegment> embeddingStore() {
        String pineconeApiKey = System.getenv("PINECONE_API_KEY");
        
        if (pineconeApiKey == null || pineconeApiKey.trim().isEmpty()) {
            logger.warn("PINECONE_API_KEY 未设置，使用内存向量存储");
            return new InMemoryEmbeddingStore<>();
        }

        try {
            logger.info("尝试连接Pinecone向量数据库...");
            
            // 设置系统属性以增加连接超时时间
            System.setProperty("okhttp.connect.timeout", "60");
            System.setProperty("okhttp.read.timeout", "60");
            
            EmbeddingStore<TextSegment> embeddingStore = PineconeEmbeddingStore.builder()
                    .apiKey(pineconeApiKey)
                    .index("dianxiaoer-index")
                    .nameSpace("dianxiaoer-namespace")
                    .build();
            
            logger.info("Pinecone向量数据库连接成功");
            return embeddingStore;
        } catch (Exception e) {
            logger.error("Pinecone连接失败，回退到内存向量存储: {}", e.getMessage());
            logger.warn("注意：使用内存存储，应用重启后向量数据将丢失");
            return new InMemoryEmbeddingStore<>();
        }
    }


}
